package org.nobject.common.swing.g;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;

import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.TableColumnModel;

/**
 * EditableHeaderUI
 * 
 * @author bianrongjun
 * @version 1.0
 */
class GEditableHeaderUI extends BasicTableHeaderUI {

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.plaf.basic.BasicTableHeaderUI#createMouseInputListener()
	 */
	protected MouseInputListener createMouseInputListener() {
		return new MouseInputHandler((GEditableHeader) header);
	}

	/**
	 * MouseInputHandler
	 * 
	 * @author bianrongjun
	 * @version 1.0
	 */
	public class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler {
		/** dispatchComponent */
		private Component dispatchComponent;

		/** header */
		protected GEditableHeader header;

		/**
		 * 构造函数
		 * 
		 * @param header
		 */
		public MouseInputHandler(GEditableHeader header) {
			this.header = header;
		}

		/** setDispatchComponent */
		private void setDispatchComponent(MouseEvent e) {
			Component editorComponent = header.getEditorComponent();
			Point p = e.getPoint();
			Point p2 = SwingUtilities.convertPoint(header, p, editorComponent);
			dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent, p2.x, p2.y);
		}

		/** repostEvent */
		private boolean repostEvent(MouseEvent e) {
			if (dispatchComponent == null) {
				return false;
			}
			MouseEvent e2 = SwingUtilities.convertMouseEvent(header, e, dispatchComponent);
			dispatchComponent.dispatchEvent(e2);
			return true;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler#mousePressed(java.awt.event.MouseEvent)
		 */
		public void mousePressed(MouseEvent e) {
			if (!SwingUtilities.isLeftMouseButton(e)) return;
			super.mousePressed(e);
			
			Point p = e.getPoint();
			TableColumnModel columnModel = header.getColumnModel();
			int index = columnModel.getColumnIndexAtX(p.x);
			if (index != -1) {
				if (header.editCellAt(index, e)) {
					setDispatchComponent(e);
					repostEvent(e);
				}
			}
//			if (header.getResizingColumn() == null) {
//				Point p = e.getPoint();
//				TableColumnModel columnModel = header.getColumnModel();
//				int index = columnModel.getColumnIndexAtX(p.x);
//				if (index != -1) {
//					if (header.editCellAt(index, e)) {
//						setDispatchComponent(e);
//						repostEvent(e);
//					}
//				}
//			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler#mouseReleased(java.awt.event.MouseEvent)
		 */
		public void mouseReleased(MouseEvent e) {
			super.mouseReleased(e);
			if (!SwingUtilities.isLeftMouseButton(e)) {
				return;
			}
			repostEvent(e);
			dispatchComponent = null;
		}

	}
}
